<template>
  <div class="app-container">
    <div class="ai-chat-container">
      <div class="chat-history" ref="chatHistory">
        <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message-container', message.role]"
        >
          <div class="avatar">
            <img
              v-if="message.role === 'assistant'"
              src="@/assets/ai-avatar.png"
              alt="AI"
            />
            <div v-else class="user-avatar">
              <i class="el-icon-user-solid"></i>
            </div>
          </div>

          <div class="message-bubble">
            <div class="message-content">
              <pre>{{ message.content }}</pre>
              <div class="message-actions">
                <el-tooltip content="复制" placement="top">
                  <i
                    class="el-icon-document-copy"
                    @click="copyText(message.content)"
                  ></i>
                </el-tooltip>
              </div>
            </div>
            <div v-if="message.loading" class="typing-indicator">
              <span class="dot"></span>
              <span class="dot"></span>
              <span class="dot"></span>
            </div>
          </div>
        </div>
      </div>

      <div class="input-container">
        <div class="input-wrapper">
          <el-input
            v-model="inputMessage"
            placeholder="有什么可以帮助您？"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            resize="none"
            @keyup.enter.native="sendMessage"
            :disabled="loading"
          ></el-input>
          <el-button
            type="primary"
            :class="['send-btn', { 'loading-btn': loading }]"
            @click="sendMessage"
          >
            <i v-if="!loading" class="el-icon-s-promotion"></i>
            <span v-else class="loading-dots">
              <span class="dot">.</span><span class="dot">.</span
              ><span class="dot">.</span>
            </span>
          </el-button>
        </div>
        <div class="footer-tips">
          <span class="hint">本功能由数字牧马人项目组提供</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
const LOCAL_CONFIG = {
  API_KEY: "50f9a243-b742-45ce-961d-f5fe66c4e93f",
  BASE_URL: "https://ark.cn-beijing.volces.com/api/v3",
  MODEL_ID: "ep-20250521144115-xn4dd",
  SDK_URL: "https://unpkg.com/openai@4.0.0/browser/openai.browser.min.js",
};

export default {
  name: "ZhinengGPT3",
  data() {
    return {
      inputMessage: "",
      messages: JSON.parse(localStorage.getItem("aiChatHistory")) || [],
      loading: false,
      openai: null,
      sdkLoaded: false,
      initError: null,
    };
  },
  async mounted() {
    await this.loadSDK();
    await this.initializeAI();
    this.scrollToBottom();
  },
  watch: {
    messages: {
      handler(newVal) {
        const saveData = newVal.filter((msg) => !msg.loading);
        localStorage.setItem("aiChatHistory", JSON.stringify(saveData));
      },
      deep: true,
    },
  },
  methods: {
    async loadSDK() {
      try {
        if (typeof window.OpenAI !== "undefined") return;

        await new Promise((resolve, reject) => {
          const script = document.createElement("script");
          script.src = LOCAL_CONFIG.SDK_URL;
          script.onload = resolve;
          script.onerror = () => reject(new Error("AI引擎加载失败"));
          document.head.appendChild(script);
        });

        this.sdkLoaded = true;
      } catch (error) {
        this.initError = error.message;
      }
    },

    async initializeAI() {
      try {
        if (!this.sdkLoaded) throw new Error("SDK未加载");

        this.openai = new window.OpenAI({
          apiKey: LOCAL_CONFIG.API_KEY,
          baseURL: LOCAL_CONFIG.BASE_URL,
          dangerouslyAllowBrowser: true,
        });

        // 简单验证连接
        await this.openai.chat.completions.create({
          messages: [{ role: "user", content: "ping" }],
          model: LOCAL_CONFIG.MODEL_ID,
          max_tokens: 1,
        });
      } catch (error) {
        this.initError = `初始化失败: ${error.message}`;
        throw error;
      }
    },

    async sendMessage() {
      if (!this.sdkLoaded || this.initError) {
        this.$message.error("AI引擎未就绪");
        return;
      }

      if (!this.inputMessage.trim() || this.loading) return;

      try {
        this.loading = true;
        this.messages.push({
          role: "user",
          content: this.inputMessage,
        });
        this.inputMessage = "";

        const aiMessage = {
          role: "assistant",
          content: "",
          loading: true,
        };
        this.messages.push(aiMessage);

        const stream = await this.openai.chat.completions.create({
          messages: this.messages.filter((m) => m.role !== "assistant"),
          model: LOCAL_CONFIG.MODEL_ID,
          stream: true,
        });

        for await (const part of stream) {
          const content = part.choices[0]?.delta?.content || "";
          this.messages[this.messages.length - 1].content += content;
          this.scrollToBottom();
        }
      } catch (error) {
        this.$message.error(`请求失败: ${error.message}`);
        this.messages.splice(-2, 2);
      } finally {
        this.loading = false;
        if (this.messages.length > 0) {
          this.messages[this.messages.length - 1].loading = false;
        }
      }
    },

    scrollToBottom() {
      this.$nextTick(() => {
        this.$refs.chatHistory.scrollTop = this.$refs.chatHistory.scrollHeight;
      });
    },

    copyText(text) {
      navigator.clipboard
        .writeText(text)
        .then(() => {
          this.$message.success("已复制到剪贴板");
        })
        .catch(() => {
          this.$message.error("复制失败");
        });
    },
  },
};
</script>

<style scoped>
/* 保持与index.vue相同的样式 */
.app-container {
  height: 100vh;
  padding: 20px;
  background-color: #f0f2f5;
}

.ai-chat-container {
  max-width: 800px;
  height: 80vh;
  margin: 0 auto;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background: #fff;
  display: flex;
  flex-direction: column;
}

.chat-history {
  flex: 1;
  padding: 20px;
  background: #f7f8fa;
  overflow-y: auto;
  min-height: 200px;
}

.message-container {
  display: flex;
  margin: 12px 0;
  gap: 12px;
  min-height: 40px;
}

/* ... 保持原有所有样式不变 ... */
</style>
